﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MiniExcelLibs;
using thinger.DataConvertLib;
using thinger.MTHModels;

namespace thinger.MTHProject
{
    public partial class FrmVarlableConfig : Form
    {
        public FrmVarlableConfig()
        {
            InitializeComponent();
            //设置数据类型
            this.cbbDataType.DataSource = Enum.GetNames(typeof(DataType));

            //取消自动创建列
            this.dgvVarlableList.AutoGenerateColumns = false;
            //加载数据
            DataLoad();

            //设置通信组的名称
            foreach (var item in groupAll)
            {
                this.cbbGroupName.Items.Add(item.GroupName);
            }

            //刷新数据
            Refresh();

        }
        //保存文件的路径
        private string groupPath = Application.StartupPath + "\\Config\\Group.xlsx";

        private string varlablePath = Application.StartupPath + "\\Config\\Varlable.xlsx";

        private List<Group> groupAll = new List<Group>();

        private List<Varlable> varlableAll = new List<Varlable>();

        //保存通信组设置
        private void btnAdd_Click(object sender, EventArgs e)
        {

            if (!isVarName(this.txtVarName.Text.Trim()))
            {
                try
                {
                    varlableAll.Add(new Varlable()
                    {
                        VarName = this.txtVarName.Text,
                        GroupName = this.cbbGroupName.Text,
                        Start = Convert.ToInt32(this.nUpStart.Value),
                        OffsetOrLength = (float)this.nUpOffsetOrLength.Value,
                        Offset = (float)this.nUpOffset.Value,
                        DataType = this.cbbDataType.Text.Trim(),
                        VarScale = (float)this.nUpVarScale.Value,
                        PosAlarm = this.cbPosAlarm.Checked,
                        NegAlarm = this.cbNegAlarm.Checked,
                        Remark = this.textRemark.Text,

                    });
                    //保存
                    MiniExcel.SaveAs(varlablePath, varlableAll,overwriteFile:true);
                    new FrmMsgBoxWithOutAck("成功", "添加成功").Show();
                    //刷新
                    Refresh();
                }
                catch (Exception ex)
                {

                    new FrmMsgBoxWithOutAck("失败", "失败" + ex.Message).Show();
                }
                
            }
            else 
            {
                new FrmMsgBoxWithOutAck("添加失败","变量已经存在").Show();
            }

            


        }

        private bool isVarName(string varName) 
        { 
            return varlableAll.FindAll(x => x.VarName == varName).Count > 0;
        }

        private void DataLoad()
        {
            //建立目标目录

            string varlableName = Path.GetDirectoryName(varlablePath);

            if (!Directory.Exists(varlableName))
            {
                Directory.CreateDirectory(varlableName);

            }

            try
            {
                List<Group> groups = MiniExcel.Query<Group>(groupPath).ToList();
                if (groups.Count > 0)
                {
                    groupAll = groups;
                }
            }
            catch (Exception)
            {
                new FrmMsgBoxWithOutAck("通信组加载失败", "先添加相关的通信组");
            }
            try
            {
                
                List<Varlable> varlables = MiniExcel.Query<Varlable>(varlablePath).ToList();
                
                if (varlables.Count > 0 ) 
                {
                    varlableAll = varlables;
                }

            }
            catch (Exception)
            {
                return;
            }


        }

        private void Refresh()
        {
            if (varlableAll.Count > 0 && varlableAll != null)
            {
                this.dgvVarlableList.DataSource = null;
                this.dgvVarlableList.DataSource = varlableAll;
            }




        }


        private void btnCanel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (isVarName(this.txtVarName.Text.Trim()))
            {
                DialogResult dialogResult = new FrmMsgBoxWithAck("删除确定", "是否删除").ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    try
                    {
                        Varlable varlable = varlableAll.Find(a => a.VarName == this.txtVarName.Text.Trim());

                        varlableAll.Remove(varlable);


                        MiniExcel.SaveAs(varlablePath, varlableAll, overwriteFile: true);

                        //刷新
                        Refresh();
                    }
                    catch (Exception ex)
                    {
                        new FrmMsgBoxWithOutAck("删除失败", "失败" + ex.Message).Show();

                    }
                    

                }
            }
            else
            {
                new FrmMsgBoxWithOutAck("删除失败", "变量名不存在");
            }

        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (isVarName(this.txtVarName.Text.Trim()))
            {
                try
                {
                    Varlable varlable = varlableAll.Find(a => a.VarName == this.txtVarName.Text.Trim());

                    varlable.VarName = this.txtVarName.Text.Trim();
                    varlable.GroupName = this.cbbGroupName.Text;
                    varlable.Start = Convert.ToInt32(this.nUpStart.Value);
                    varlable.OffsetOrLength = (float)this.nUpOffsetOrLength.Value;
                    varlable.Offset = (float)this.nUpOffset.Value;
                    varlable.DataType = this.cbbDataType.Text.Trim();
                    varlable.VarScale = (float)this.nUpVarScale.Value;
                    varlable.PosAlarm = this.cbPosAlarm.Checked;
                    varlable.NegAlarm = this.cbNegAlarm.Checked;
                    varlable.Remark = this.textRemark.Text;

                    MiniExcel.SaveAs(varlablePath, varlableAll, overwriteFile: true);

                    //刷新
                    Refresh();
                }
                catch (Exception ex)
                {

                    new FrmMsgBoxWithOutAck("更新失败", "失败" + ex.Message);
                }
               
            }
            else 
            {
                new FrmMsgBoxWithOutAck("更新失败", "变量名不存在");
            }



        }


        #region 无边框拖动
        private Point mPoint;
        private void Panel_MouseDown(object sender, MouseEventArgs e)
        {
            mPoint = new Point(e.X, e.Y);
        }
        private void Panel_MouseMove(object sender, MouseEventArgs e)
        {
            //鼠标左键点击
            if (e.Button == MouseButtons.Left)
            {
                this.Location = new Point(this.Location.X + (e.X - mPoint.X), this.Location.Y + (e.Y - mPoint.Y));
            }

        }
        #endregion

        #region 设置自动索引
        private void dgvGroupList_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, this.dgvVarlableList.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), this.dgvVarlableList.RowHeadersDefaultCellStyle.Font, rectangle, this.dgvVarlableList.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
        #endregion

        #region 给空白的数据加“---”
        private void dgvGroupList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                object value = this.dgvVarlableList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

                if (value == null || value.ToString().Length == 0)
                {
                    e.Value = "---";
                }
            }
        }
        #endregion
        /// <summary>
        /// 点击单元格，回溯数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvVarlableList_CellClick(object sender, DataGridViewCellEventArgs e)
        {

            if (e.RowIndex >= 0) 
            {
                Varlable varlable = varlableAll[e.RowIndex];

                if (varlable != null)
                {
                    this.txtVarName.Text = varlable.VarName;
                    this.cbbGroupName.Text = varlable.GroupName;
                    this.nUpStart.Value = varlable.Start;
                    this.nUpOffsetOrLength.Value = (decimal)varlable.OffsetOrLength;
                    this.nUpOffset.Value = (decimal)varlable.Offset;
                    this.cbbDataType.Text = varlable.DataType;
                    this.nUpVarScale.Value = (decimal)varlable.VarScale;
                    this.cbPosAlarm.Checked = varlable.PosAlarm;
                    this.cbNegAlarm.Checked = varlable.NegAlarm;
                    this.textRemark.Text = varlable.Remark;
                }
            }
            

        }
    }
}
